package com.example.wzsdk.login;

import com.example.wzsdk.callback.LoginStateCallback;
import com.example.wzsdk.callback.ReceiveData;
import com.example.wzsdk.commpg.SetPackages;
import com.example.wzsdk.constant.ClientState;
import com.example.wzsdk.tools.ToolsClass;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;

/**
 * Created by SunLight on 2017/8/11.
 */

public class LoginThread extends Thread {
    TargetInfo targetInfo;
    private SetPackages setPackages;
    private Socket socket = null;
    private OutputStream outputStream;
    private InputStream inputStream;
    private ReceiveData receiveData;
    private LoginStateCallback loginState;


    public LoginThread(TargetInfo targetInfo, SetPackages setPackages, LoginStateCallback loginState) {
        this.targetInfo = targetInfo;
        this.setPackages = setPackages;
        this.loginState = loginState;
    }

    public void setReceiveData(ReceiveData receiveData) {
        this.receiveData = receiveData;
    }

    @Override
    public void run() {
        try {
            socket = new Socket(targetInfo.getIp(), targetInfo.getPort());
            outputStream = socket.getOutputStream();
            inputStream = socket.getInputStream();
            outputStream.write(setPackages.ScanPg());
            byte[] s = new byte[1024 * 3];
            int i;
            while ((i = inputStream.read(s)) != -1) {
                receiveData.receive(Arrays.copyOf(s, i));
            }
        } catch (IOException e) {
            e.printStackTrace();
            loginState.LoginStatus(false, ToolsClass.Dut_ID(setPackages.getData().SnHash, 10));
            setPackages.getData().ListClear();
            disconnect();
        }
    }

    /**
     * @User SunLight
     * @Data 2018/1/11 16:12
     * @Method 断开连接
     **/
    public void disconnect() {
        closeSocket();
        setPackages.getData().isState = ClientState.Disconnected;
    }


    private void closeSocket() {
        if (socket != null) {
            try {
                outputStream.close();
                inputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @User SunLight
     * @Data 2018/1/11 16:12
     * @Method 发送方法
     **/
    public void Send(byte[] bytes) {
        try {
            outputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
